﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using DevEx.Thanh.reports;
using DevExpress.XtraEditors;
using System.Xml;
using System.Data.Linq;
using System.Linq;
using DevExpress.XtraGrid;
using DevExpress.Xpf;
using DevExpress.Data;
using DevExpress.Utils;
using DevExpress.XtraGrid.Views.Grid;
using System.Collections;
using DevEx.Thanh.Class;
using DevEx.Thanh.UserControl;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraReports.UI;

namespace DevEx
{
    public partial class ucPhieuNhap : DevExpress.XtraEditors.XtraUserControl
    {
        private int _ID_DPNX;
        private int _ID_DonVi;
        private int _ID_User = GlobalVar.CurrentUser.ID_User;
        private int _ID_Kho = Convert.ToInt32(GlobalVar.CurrentUser.ID_Kho);
        private int _SoPhieu = 0;

        CDPNX m_DPNX = new CDPNX();
        QLVTDataContext dc = new QLVTDataContext();
        DataTable dtSLNX;

        public ucPhieuNhap()
        {
            InitializeComponent();
            KhoiTaoDM();
            KhoiTaoAutoCompleteVatTu();

            //So Phieu Moi
            CKho m_kho = new CKho();
            CModule_Sy module = new CModule_Sy();
            txtSoPhieu.EditValue = module.GetNewSoPhieu("N", DateTime.Now, m_kho.SelectRecordByID(_ID_Kho).KH_Kho, ref _SoPhieu);

            //Ngay Phieu
            dtpNgayPhieu.EditValue = DateTime.Now;
            lueKho.EditValue = _ID_Kho;
            CUserController m_user = new CUserController();
            lblNguoiLapPhieu.Text = "Người lập phiếu: " + m_user.SelectRecordByID(_ID_User).FullName;
            KhoiTaodtSLNX();
            KhoiTaoSLNX(0);
            FormatdtgPhieuNhap();
            KhoiTaoGiaoDien(false);
        }

        public ucPhieuNhap(int ID_DPNX)
        {
            InitializeComponent();
            _ID_DPNX = ID_DPNX;
            CDPNX m_DPNX = new CDPNX();
            _SoPhieu = Convert.ToInt32(m_DPNX.SelectRecordByID(ID_DPNX).SoPhieu);
            KhoiTaoDM();
            KhoiTaoAutoCompleteVatTu();
            KhoiTaodtSLNX();
            KhoiTaoDPNX();
            FormatdtgPhieuNhap();
            KhoiTaoGiaoDien(true);
        }

        //public int GetSoPhieu()
        //{
        //    int q = 0;
        //    QLVTDataContext dc = new QLVTDataContext();

        //    q = Convert.ToInt32((from p in dc.tblDPNXes
        //                         where p.NX == "N" && Convert.ToDateTime(p.NgayPhieu).Year == DateTime.Now.Year && Convert.ToDateTime(p.NgayPhieu).Month == DateTime.Now.Month
        //             select p.SoPhieu).Max());

        //    return q+1;
        //}

        private void ucPhieuNhap_Load(object sender, EventArgs e)
        {

        }

        public void KhoiTaoDM()
        {
            //1. Danh muc Tinh chat Nhap
            CTCNX m_TCNX = new CTCNX();
            lueTCNX.Properties.DisplayMember = "TCNX";
            lueTCNX.Properties.ValueMember = "ID_TCNX";
            lueTCNX.Properties.DataSource = m_TCNX.SelectAllRecord(true);

            //2. Danh muc Kho
            CKho m_kho = new CKho();
            lueKho.Properties.DisplayMember = "Kho";
            lueKho.Properties.ValueMember = "ID_Kho";

            lueKho.Properties.DataSource = m_kho.SelectAllRecord();
            lueKho.Properties.PopulateColumns();
            //lueKho.Properties.Columns["ID_Kho"].Visible = false;

            //3. Danh muc Hop Dong
            CHopDong m_hopdong = new CHopDong();
            lueHopDong.Properties.DisplayMember = "SoHopDong";
            lueHopDong.Properties.ValueMember = "ID_HopDong";
            lueHopDong.Properties.DataSource = m_hopdong.SelectAllRecord();
        }


        public void KhoiTaoDPNX()
        {
            var DPNX = m_DPNX.SelectRecordByID(_ID_DPNX);

            CKho m_kho = new CKho();
            CModule_Sy module = new CModule_Sy();
            txtSoPhieu.EditValue = module.GetSoPhieu(_ID_DPNX);

            //if (Convert.ToDateTime(DPNX.NgayPhieu).Month < 10)
            //    txtSoPhieu.EditValue = DPNX.SoPhieu + "/0" + Convert.ToDateTime(DPNX.NgayPhieu).Month.ToString() + Convert.ToDateTime(DPNX.NgayPhieu).Year.ToString().Substring(2,2);
            //else
            //    txtSoPhieu.EditValue = DPNX.SoPhieu + "/" + Convert.ToDateTime(DPNX.NgayPhieu).Month.ToString() + Convert.ToDateTime(DPNX.NgayPhieu).Year.ToString().Substring(2, 2);

            dtpNgayPhieu.EditValue = DPNX.NgayPhieu;
            lueTCNX.EditValue = DPNX.ID_TCNX;
            lueKho.EditValue = DPNX.ID_Kho;
            txtLyDoNhap.EditValue = DPNX.LyDoNhapXuat;

            _ID_DonVi = Convert.ToInt32(DPNX.ID_DonVi);
            txtDonViBan.EditValue = DPNX.tblDonVi.DonVi;
            txtDiaChi.EditValue = DPNX.tblDonVi.DiaChi;

            txtHoaDon.EditValue = DPNX.HoaDon;
            CUserController m_user = new CUserController();
            lblNguoiLapPhieu.Text = "Người lập phiếu: " + m_user.SelectRecordByID(Convert.ToInt32(DPNX.ID_CreatedUser)).FullName;

            var list_ton = (from p in dc.tblSLNXes
                            where p.ID_DPNX == DPNX.ID_DPNX
                            select p);

            int ID_HopDong = 0;

            foreach (tblSLNX ton in list_ton)
            {
                if (ton.tblTon.ID_HopDong != null)
                    ID_HopDong = Convert.ToInt32(ton.tblTon.ID_HopDong);
                break;
            }

            if (ID_HopDong != 0)
            {
                lueHopDong.EditValue = ID_HopDong;
            }

            KhoiTaoSLNX(DPNX.ID_DPNX);
        }

        public void KhoiTaoSLNX(int ID_DPNX)
        {
            //CSLNX m_SLNX = new CSLNX();
            //dtgPhieuNhap.DataSource = m_SLNX.SelectAllRecord(ID_DPNX);

            var q = from p in dc.tblSLNXes
                    where p.ID_DPNX == ID_DPNX
                    select new
                    {
                        p.ID_SLNX,
                        p.ID_MatHang,
                        p.tblTon.ID_VatTu,
                        p.tblTon.tblVatTu.VatTu,
                        p.tblTon.tblVatTu.MaKyHieu,
                        p.tblTon.NamSX,
                        p.tblTon.ID_CCL,
                        p.tblTon.ID_NguonVatTu,
                        p.tblTon.Gia,
                        p.SLKH,
                        ThanhTien = p.SLKH * p.tblTon.Gia,
                        p.tblTon.SoTheKho,
                        p.tblTon.Code,
                        p.tblTon.TangKeKhoang,
                        p.GhiChu
                    };

            try { dtSLNX.Rows.Clear(); }
            catch { };

            foreach (var ton in q)
            {
                DataRow row = dtSLNX.NewRow();
                row["ID_SLNX"] = ton.ID_SLNX;
                row["ID_MatHang"] = ton.ID_MatHang;
                row["ID_VatTu"] = ton.ID_VatTu;
                row["VatTu"] = ton.VatTu;
                row["Code"] = ton.Code;
                row["MaKyHieu"] = ton.MaKyHieu;
                row["ID_CCL"] = ton.ID_CCL;
                row["Gia"] = ton.Gia;
                row["NamSX"] = ton.NamSX ?? "00/0000";
                row["SLKH"] = ton.SLKH ?? 0;
                row["ThanhTien"] = ton.ThanhTien;
                row["ID_NguonVatTu"] = ton.ID_NguonVatTu;
                row["SoTheKho"] = ton.SoTheKho;
                row["TangKeKhoang"] = ton.TangKeKhoang;
                row["GhiChu"] = ton.GhiChu;
                row["Status"] = 0;//binh thuong
                row["Del"] = 0;//binh thuong
                dtSLNX.Rows.Add(row);
            }

            dtgPhieuNhap.DataSource = dtSLNX;
        }

        public void FormatdtgPhieuNhap()
        {
            gridView1.OptionsView.ShowFooter = true;
            gridView1.Columns.ColumnByFieldName("ID_SLNX").Visible = false;
            gridView1.Columns.ColumnByFieldName("ID_VatTu").Visible = false;
            gridView1.Columns.ColumnByFieldName("ID_MatHang").Visible = false;
            gridView1.Columns.ColumnByFieldName("Status").Visible = false;
            //gridView1.Columns.ColumnByFieldName("Code").Visible = false;

            //Columns VatTu
            var cl_VatTu = gridView1.Columns.ColumnByFieldName("VatTu");
            cl_VatTu.Width = 150;
            cl_VatTu.Caption = "Vật Tư";
            cl_VatTu.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Near;
            cl_VatTu.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;
            cl_VatTu.AppearanceCell.BackColor = Color.Azure;

            //Columns CCL
            var cl_CCL = gridView1.Columns.ColumnByFieldName("ID_CCL");
            cl_CCL.Width = 50;
            cl_CCL.Caption = "CCL";
            cl_CCL.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Center;
            cl_CCL.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;

            //Columns Del
            var cl_Del = gridView1.Columns.ColumnByFieldName("Del");
            cl_Del.Width = 30;
            cl_Del.Caption = "Del";
            cl_Del.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Center;
            cl_Del.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;

            //Columns Nguon Nhap
            var cl_NguonVatTu = gridView1.Columns.ColumnByFieldName("ID_NguonVatTu");
            cl_NguonVatTu.Width = 80;
            cl_NguonVatTu.Caption = "N. H.Toán";
            cl_NguonVatTu.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Center;
            cl_NguonVatTu.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;

            //format TCNX
            DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit repositoryItemLookUpEdit_NguonVatTu = new DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit();
            CNguonVatTu m_nvt = new CNguonVatTu();
            repositoryItemLookUpEdit_NguonVatTu.DataSource = m_nvt.SelectAllRecord();

            repositoryItemLookUpEdit_NguonVatTu.DisplayMember = "NguonVatTu";
            repositoryItemLookUpEdit_NguonVatTu.ValueMember = "ID_NguonVatTu";
            repositoryItemLookUpEdit_NguonVatTu.Columns.AddRange(new DevExpress.XtraEditors.Controls.LookUpColumnInfo[] {
            new DevExpress.XtraEditors.Controls.LookUpColumnInfo("NguonVatTu", "NguonVatTu", 20, DevExpress.Utils.FormatType.None, "", true, DevExpress.Utils.HorzAlignment.Default, DevExpress.Data.ColumnSortOrder.None)});
            //repositoryItemLookUpEdit_NguonVatTu.Appearance.Font = new Font(this.Appearance.Font.Name, 10);
            cl_NguonVatTu.ColumnEdit = repositoryItemLookUpEdit_NguonVatTu;

            //Columns NamSX
            var cl_NamSX = gridView1.Columns.ColumnByFieldName("NamSX");
            cl_NamSX.Width = 50;
            cl_NamSX.Caption = "Năm SX";
            cl_NamSX.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Center;
            cl_NamSX.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;

            //Columns MaKyHieu
            var cl_MaKyHieu = gridView1.Columns.ColumnByFieldName("MaKyHieu");
            cl_MaKyHieu.Caption = "Mã K.Hiệu";
            cl_MaKyHieu.Width = 100;
            cl_MaKyHieu.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Near;
            cl_MaKyHieu.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;
            cl_MaKyHieu.AppearanceCell.BackColor = Color.Azure;

            //Columns SoTheKho
            var cl_SoTheKho = gridView1.Columns.ColumnByFieldName("SoTheKho");
            cl_SoTheKho.Width = 60;
            cl_SoTheKho.Caption = "Thẻ Kho";
            cl_SoTheKho.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Center;
            cl_SoTheKho.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;
            cl_SoTheKho.AppearanceCell.BackColor = Color.Azure;

            //Columns Code
            var cl_Code = gridView1.Columns.ColumnByFieldName("Code");
            cl_Code.Width = 30;
            cl_Code.Caption = "Code";
            cl_Code.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Center;
            cl_Code.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;
            cl_Code.AppearanceCell.BackColor = Color.Azure;

            //Columns TangKeKhoang
            var cl_TangKeKhoang = gridView1.Columns.ColumnByFieldName("TangKeKhoang");
            cl_TangKeKhoang.Width = 40;
            cl_TangKeKhoang.Caption = "Vị trí";
            cl_TangKeKhoang.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Center;
            cl_TangKeKhoang.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;


            //Columns GhiChu
            var cl_GhiChu = gridView1.Columns.ColumnByFieldName("GhiChu");
            cl_GhiChu.Caption = "Ghi chú";
            cl_GhiChu.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Near;
            cl_GhiChu.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;


            //Columns Gia
            var cl_Gia = gridView1.Columns.ColumnByFieldName("Gia");
            cl_Gia.Width = 70;
            cl_Gia.Caption = "Đơn giá";
            cl_Gia.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Far;
            cl_Gia.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;
            cl_Gia.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
            cl_Gia.DisplayFormat.FormatString = "n0";

            //Columns ThanhTien           
            var cl_ThanhTien = gridView1.Columns["ThanhTien"];
            cl_ThanhTien.Width = 80;
            cl_ThanhTien.Caption = "Thành tiền";
            cl_ThanhTien.Summary.Add(DevExpress.Data.SummaryItemType.Sum, "ThanhTien", "{0:n0}");
            cl_ThanhTien.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Far;
            cl_ThanhTien.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;
            cl_ThanhTien.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
            cl_ThanhTien.OptionsColumn.AllowEdit = false;
            cl_ThanhTien.DisplayFormat.FormatString = "n0";


            //Columns SLTonKH
            var cl_SLTonKH = gridView1.Columns.ColumnByFieldName("SLKH");
            cl_SLTonKH.Width = 60;
            cl_SLTonKH.Caption = "SLKH";
            cl_SLTonKH.AppearanceCell.TextOptions.HAlignment = HorzAlignment.Far;
            cl_SLTonKH.AppearanceHeader.TextOptions.HAlignment = HorzAlignment.Center;
            cl_SLTonKH.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
            cl_SLTonKH.DisplayFormat.FormatString = "n0";

            //repositoryItemLookUpEdit1.AutoHeight = false;
            //repositoryItemLookUpEdit1.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] {
            //new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo)});
            //repositoryItemLookUpEdit1.DropDownRows = 10;
            //repositoryItemLookUpEdit1.Name = "repositoryItemLookUpEdit1";
            //repositoryItemLookUpEdit1.PopupWidth = 220;

            //format CCL
            DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit repositoryItemLookUpEdit_CCL = new DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit();
            CCCL m_ccl = new CCCL();
            repositoryItemLookUpEdit_CCL.DataSource = m_ccl.SelectAllRecord();

            repositoryItemLookUpEdit_CCL.DisplayMember = "CCL";
            repositoryItemLookUpEdit_CCL.ValueMember = "ID_CCL";
            repositoryItemLookUpEdit_CCL.Columns.AddRange(new DevExpress.XtraEditors.Controls.LookUpColumnInfo[] {
            new DevExpress.XtraEditors.Controls.LookUpColumnInfo("CCL", "CCL", 20, DevExpress.Utils.FormatType.None, "", true, DevExpress.Utils.HorzAlignment.Default, DevExpress.Data.ColumnSortOrder.None)});
            ((DevExpress.XtraGrid.Views.Base.ColumnView)dtgPhieuNhap.MainView).Columns["ID_CCL"].ColumnEdit = repositoryItemLookUpEdit_CCL;

            //RepositoryItemTextEdit  de = new RepositoryItemTextEdit();
            ////de.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.DateTime;
            //de.Mask.UseMaskAsDisplayFormat = true;
            //de.Mask.EditMask = "MM/yyyy";
            //gridView1.Columns["NamSX"].ColumnEdit = de;
        }

        private void gridView1_CustomDrawRowFooterCell(object sender, DevExpress.XtraGrid.Views.Grid.FooterCellCustomDrawEventArgs e)
        {
            //e.Appearance.BackColor = Color.Red;
            //Change the background color
            e.Appearance.BackColor = Color.Red;
            //Font f = new Font(e.Appearance.Font.Name, 10, FontStyle.Bold);
            //e.Appearance.Font = f;
            //Paint using the new background color
            e.Painter.DrawObject(e.Info);
            //Prevent default painting
            e.Handled = true;
        }

        public void KhoiTaodtSLNX()
        {
            dtSLNX = new DataTable();
            dtSLNX.Columns.Add("Del", typeof(Boolean));//0: binh thuong, 1: xoa
            dtSLNX.Columns.Add("ID_SLNX", typeof(int));
            dtSLNX.Columns.Add("ID_MatHang", typeof(int));
            dtSLNX.Columns.Add("ID_VatTu", typeof(int));
            dtSLNX.Columns.Add("VatTu", typeof(String));
            dtSLNX.Columns.Add("MaKyHieu", typeof(String));
            dtSLNX.Columns.Add("NamSX", typeof(String));
            dtSLNX.Columns.Add("ID_CCL", typeof(int));
            dtSLNX.Columns.Add("Gia", typeof(Double));
            dtSLNX.Columns.Add("SLKH", typeof(Double));
            dtSLNX.Columns.Add("ThanhTien", typeof(Double));
            dtSLNX.Columns.Add("ID_NguonVatTu", typeof(int));
            dtSLNX.Columns.Add("TangKeKhoang", typeof(String));
            dtSLNX.Columns.Add("GhiChu", typeof(String));
            dtSLNX.Columns.Add("SoTheKho", typeof(String));
            dtSLNX.Columns.Add("Code", typeof(int));
            dtSLNX.Columns.Add("Status", typeof(int));//0: binh thuong, 1: them, 2: sua, 3: xoa            
        }

        AutoCompleteStringCollection customSource = new AutoCompleteStringCollection();

        public void KhoiTaoAutoCompleteVatTu()
        {
            //CVatTu m_vattu = new CVatTu();
            //IQueryable<tblVatTu> m_vattuSelectAllRecord = m_vattu.SelectAllRecord();
            var listVatTu = from p in dc.tblVatTus
                            where p.Cuoi == true
                            orderby p.VatTu
                            select p;

            foreach (tblVatTu vattu in listVatTu)
            {
                customSource.Add(vattu.VatTu);
            }
        }

        public void CreatNewRowVatTu(tblVatTu obj_VatTu)
        {
            gridView1.AddNewRow();

            int rowHandle = gridView1.GetRowHandle(gridView1.DataRowCount);
            if (gridView1.IsNewItemRow(rowHandle))
            {
                gridView1.SetRowCellValue(rowHandle, gridView1.Columns["VatTu"], obj_VatTu.VatTu);
                gridView1.SetRowCellValue(rowHandle, gridView1.Columns["ID_VatTu"], obj_VatTu.ID_VatTu);
                gridView1.SetRowCellValue(rowHandle, gridView1.Columns["ID_CCL"], 1);
                gridView1.SetRowCellValue(rowHandle, gridView1.Columns["Gia"], 0);
                gridView1.SetRowCellValue(rowHandle, gridView1.Columns["SLKH"], 0);
                gridView1.SetRowCellValue(rowHandle, gridView1.Columns["MaKyHieu"], "");
                gridView1.SetRowCellValue(rowHandle, gridView1.Columns["Status"], 1);
            }
            gridView1.UpdateCurrentRow();
        }

        public void CreatNewRowMatHang(int ID_MatHang)
        {
            gridView1.AddNewRow();

            int rowHandle = gridView1.GetRowHandle(gridView1.DataRowCount);

            CTon m_ton = new CTon();
            tblTon obj_ton = m_ton.SelectRecordByID(ID_MatHang);
            if (gridView1.IsNewItemRow(rowHandle))
            {
                gridView1.SetRowCellValue(rowHandle, gridView1.Columns["ID_VatTu"], obj_ton.ID_VatTu);
                gridView1.SetRowCellValue(rowHandle, gridView1.Columns["VatTu"], obj_ton.tblVatTu.VatTu);
                gridView1.SetRowCellValue(rowHandle, gridView1.Columns["ID_CCL"], obj_ton.ID_CCL);
                gridView1.SetRowCellValue(rowHandle, gridView1.Columns["Gia"], obj_ton.Gia);
                gridView1.SetRowCellValue(rowHandle, gridView1.Columns["SLKH"], 0);
                gridView1.SetRowCellValue(rowHandle, gridView1.Columns["MaKyHieu"], obj_ton.tblVatTu.MaKyHieu);
                gridView1.SetRowCellValue(rowHandle, gridView1.Columns["ID_NguonVatTu"], obj_ton.ID_NguonVatTu);
                gridView1.SetRowCellValue(rowHandle, gridView1.Columns["NamSX"], obj_ton.NamSX);
                gridView1.SetRowCellValue(rowHandle, gridView1.Columns["SoTheKho"], obj_ton.SoTheKho);
                gridView1.SetRowCellValue(rowHandle, gridView1.Columns["TangKeKhoang"], obj_ton.TangKeKhoang);
                gridView1.SetRowCellValue(rowHandle, gridView1.Columns["Status"], 1);
            }
            gridView1.UpdateCurrentRow();
        }

        private void btnThem_Click(object sender, EventArgs e)
        {
            KhoiTaoGiaoDien(false);
            Clear();
        }

        private void btnSua_Click(object sender, EventArgs e)
        {
            KhoiTaoGiaoDien(false);
        }

        private void btnXoa_Click(object sender, EventArgs e)
        {
            // xóa phiếu Nhập
            var DPNX = m_DPNX.SelectRecordByID(_ID_DPNX);

            // Kiểm tra phiếu đã được xác nhận chưa
            if (DPNX.ID_ApproveUser != null)
            {
                MessageBox.Show("Phiếu đã được xác nhận, hủy xác nhận trước khi xóa");
                return;
            }

            //Kiểm tra người lập phiếu
            if (DPNX.ID_CreatedUser == _ID_User)
            {
                String SoPhieu = txtSoPhieu.Text;
                DialogResult dialogResult = MessageBox.Show("Bạn muốn xóa phiếu số: " + SoPhieu, "Chú ý", MessageBoxButtons.YesNo);
                if (dialogResult == DialogResult.Yes)
                {
                    //Xoa phieu
                    m_DPNX.Delete(_ID_DPNX);

                    //Refesh phiếu
                    lueTCNX.Focus();
                    KhoiTaoGiaoDien(false);
                    Clear();
                }

            }
            else
                MessageBox.Show("Bạn không phải người lập phiếu");
        }

        private void btnGhi_Click(object sender, EventArgs e)
        {
            //1.  Kiểm tra dữ liệu
            //1.  Kiểm tra dữ liệu
            //1.1 Kiểm tra chọn Kho
            if (lueKho.EditValue == null)
            {
                MessageBox.Show("Bạn chưa chọn Kho");
                lueKho.Focus();
                return;
            }
            //1.2 Kiểm tra chọn TCNX và Sản phẩm
            if (lueTCNX.EditValue == null)
            {
                MessageBox.Show("Bạn chưa chọn Tính chất nhập");
                lueTCNX.Focus();
                return;
            }

            //1.3 Kiểm tra DVGN
            if (_ID_DonVi == 0)
            {
                MessageBox.Show("Bạn chưa chọn Đơn vị bán hàng");
                txtDonViBan.Focus();
                return;
            }



            //1.4 Kiểm tra Nguồn nhập, SLKH, NamSX, trùng mặt hàng
            for (int i = 0; i < gridView1.RowCount; i++)
            {
                ////1.4.1 Kiểm tra trùng dữ liệu
                //for (int j = 0; j < gridView1.RowCount; j++)
                //{
                //    int ID_VatTu_i = Convert.ToInt32(gridView1.GetRowCellValue(i, gridView1.Columns["ID_VatTu"]));
                //    if (i != j)
                //    {
                //        int ID_VatTu_j = Convert.ToInt32(gridView1.GetRowCellValue(j, gridView1.Columns["ID_VatTu"]));
                //        if (ID_VatTu_i == ID_VatTu_j)
                //        {
                //            String MaKyHieu_j = Convert.ToString(gridView1.GetRowCellValue(j, gridView1.Columns["MaKyHieu"]));
                //            int NamSX_j = Convert.ToInt32(gridView1.GetRowCellValue(j, gridView1.Columns["NamSX"]));

                //        }                        
                //    }
                //}

                try
                {
                    int NguonTC = Convert.ToInt32(gridView1.GetRowCellValue(i, gridView1.Columns["ID_NguonVatTu"]));
                }
                catch
                {
                    MessageBox.Show("Bạn chưa chọn Nguồn Tài chính cho mặt hàng Nhập");
                    dtgPhieuNhap.Focus();
                    return;
                }

                //try
                //{
                //    //int NamSX = Convert.ToInt32(gridView1.GetRowCellValue(i, gridView1.Columns["NamSX"]));
                //}
                //catch
                //{
                //    MessageBox.Show("Bạn chưa nhập năm SX cho mặt hàng");
                //    dtgPhieuNhap.Focus();
                //    return;
                //}

                int SLKH = Convert.ToInt32(gridView1.GetRowCellValue(i, gridView1.Columns["SLKH"]));
                if (SLKH == 0)
                {
                    MessageBox.Show("Bạn chưa nhập Số lượng vật tư");
                    dtgPhieuNhap.Focus();
                    return;
                }
            }


            Double TongGiaTri = 0;
            for (int i = 0; i < gridView1.RowCount; i++)
            {
                int status = Convert.ToInt32(gridView1.GetRowCellValue(i, gridView1.Columns["Status"]));
                if (status != 3)
                {
                    Double Gia = Convert.ToDouble(gridView1.GetRowCellValue(i, gridView1.Columns["Gia"]));
                    Double SLKH = Convert.ToDouble(gridView1.GetRowCellValue(i, gridView1.Columns["SLKH"]));
                    TongGiaTri += Gia * SLKH;
                }
            }
            //2. DPNX
            tblDPNX obj_DPNX = new tblDPNX();
            CDPNX m_DPNX = new CDPNX();
            if (_ID_DPNX == 0)
            {
                //var obj_DPNX = m_DPNX.SelectRecordByID(_ID_DPNX);

                obj_DPNX.HoaDon = Convert.ToString(txtHoaDon.EditValue ?? "");
                obj_DPNX.NX = "N";
                obj_DPNX.LyDoNhapXuat = Convert.ToString(txtLyDoNhap.EditValue ?? "");
                obj_DPNX.NguoiGiaoNhan = Convert.ToString(txtNguoiGiaoNhan.EditValue ?? "");
                obj_DPNX.NgayPhieu = Convert.ToDateTime(dtpNgayPhieu.EditValue);
                obj_DPNX.ID_Kho = _ID_Kho;
                obj_DPNX.ID_TCNX = Convert.ToInt32(lueTCNX.EditValue);

                obj_DPNX.SoPhieu = _SoPhieu;
                obj_DPNX.ID_DonVi = _ID_DonVi;
                obj_DPNX.TongGiaTri = TongGiaTri;
                obj_DPNX.ID_CreatedUser = _ID_User;

                CKho m_kho = new CKho();
                obj_DPNX.DuoiPhieu = m_kho.SelectRecordByID(_ID_Kho).KH_Kho;

                _ID_DPNX = m_DPNX.Insert(obj_DPNX);
            }
            else
            {
                obj_DPNX.ID_DPNX = _ID_DPNX;
                obj_DPNX.HoaDon = Convert.ToString(txtHoaDon.EditValue ?? "");
                obj_DPNX.NX = "N";
                obj_DPNX.LyDoNhapXuat = Convert.ToString(txtLyDoNhap.EditValue ?? "");
                obj_DPNX.NguoiGiaoNhan = Convert.ToString(txtNguoiGiaoNhan.EditValue ?? "");
                obj_DPNX.NgayPhieu = Convert.ToDateTime(dtpNgayPhieu.EditValue);
                obj_DPNX.ID_Kho = Convert.ToInt32(lueKho.EditValue);
                obj_DPNX.ID_TCNX = Convert.ToInt32(lueTCNX.EditValue);

                obj_DPNX.SoPhieu = _SoPhieu;
                obj_DPNX.ID_DonVi = _ID_DonVi;
                obj_DPNX.TongGiaTri = TongGiaTri;
                obj_DPNX.ID_CreatedUser = _ID_User;

                CDPNX m_dpnx = new CDPNX();
                obj_DPNX.ID_ApproveUser = m_dpnx.SelectRecordByID(_ID_DPNX).ID_ApproveUser;

                CKho m_kho = new CKho();
                obj_DPNX.DuoiPhieu = m_kho.SelectRecordByID(_ID_Kho).KH_Kho;

                m_DPNX.Update(obj_DPNX);
            }

            // 3. Chi Tiet Nhap Xuat (SLNX)
            // 3.1 Get ID_MatHang 
            // 3.1.1 Nếu tồn tại ID_MatHang trong tồn
            // 3.1.2 Ngược lại không có trong tồn -> tạo tồn trước
            // 3.2 Update SLNX và tồn



            CTon m_ton = new CTon();
            CSLNX m_SLNX = new CSLNX();

            for (int i = 0; i < gridView1.RowCount; i++)
            {
                int status = Convert.ToInt32(gridView1.GetRowCellValue(i, gridView1.Columns["Status"]));
                if (status == 1)
                { //Thêm
                    tblTon ton = new tblTon();
                    ton.ID_VatTu = Convert.ToInt32(gridView1.GetRowCellValue(i, gridView1.Columns["ID_VatTu"]));
                    ton.ID_Kho = Convert.ToInt32(lueKho.EditValue);
                    ton.ID_CCL = Convert.ToInt32(gridView1.GetRowCellValue(i, gridView1.Columns["ID_CCL"]));
                    ton.ID_NguonVatTu = Convert.ToInt32(gridView1.GetRowCellValue(i, gridView1.Columns["ID_NguonVatTu"]));
                    ton.NamSX = Convert.ToString(gridView1.GetRowCellValue(i, gridView1.Columns["NamSX"]));
                    ton.Gia = Convert.ToDouble(gridView1.GetRowCellValue(i, gridView1.Columns["Gia"]));
                    ton.SLTonKH = Convert.ToDouble(gridView1.GetRowCellValue(i, gridView1.Columns["SLKH"]));
                    ton.SLNhapKH = Convert.ToDouble(gridView1.GetRowCellValue(i, gridView1.Columns["SLKH"]));
                    //ton.SLTH = 0;//Convert.ToDouble(gridView1.GetRowCellValue(i, gridView1.Columns["SLTH"]));
                    //ton.SLSS = 0;//Convert.ToDouble(gridView1.GetRowCellValue(i, gridView1.Columns["SLSS"]));
                    ton.NgayTaoTon = DateTime.Now;
                    ton.SoTheKho = Convert.ToString(gridView1.GetRowCellValue(i, gridView1.Columns["SoTheKho"]));
                    ton.TangKeKhoang = Convert.ToString(gridView1.GetRowCellValue(i, gridView1.Columns["TangKeKhoang"]));
                    if (lueHopDong.EditValue != null)
                        ton.ID_HopDong = Convert.ToInt32(lueHopDong.EditValue);

                    ton.ID_MatHang = m_ton.InsertNhap(ton);

                    tblSLNX objSLNX = new tblSLNX();
                    objSLNX.ID_MatHang = ton.ID_MatHang;
                    objSLNX.ID_DPNX = obj_DPNX.ID_DPNX;
                    objSLNX.SLKH = ton.SLTonKH;
                    objSLNX.ThanhTien = ton.SLTonKH * ton.Gia;
                    objSLNX.GhiChu = Convert.ToString(gridView1.GetRowCellValue(i, gridView1.Columns["GhiChu"]) ?? "");

                    m_SLNX.Insert(objSLNX);
                }

                //Xóa
                if (status == 3)
                {
                    int ID_SLNX = Convert.ToInt32(gridView1.GetRowCellValue(i, gridView1.Columns["ID_SLNX"]));
                    int ID_MatHang = Convert.ToInt32(gridView1.GetRowCellValue(i, gridView1.Columns["ID_MatHang"]));
                    double SLKH = Convert.ToDouble(gridView1.GetRowCellValue(i, gridView1.Columns["SLKH"]));
                    double SLTH = Convert.ToDouble(gridView1.GetRowCellValue(i, gridView1.Columns["SLTH"]));

                    //1. Xóa SLNX
                    m_SLNX.Delete(ID_SLNX);

                    //2. Xóa trong Tồn (SLTonKH = SLTonKH - SLKH)
                    m_ton.DeleteNhap(ID_MatHang, SLKH);

                }
                //Sửa
                if (status == 2)
                {
                    int ID_SLNX = Convert.ToInt32(gridView1.GetRowCellValue(i, gridView1.Columns["ID_SLNX"]));
                    int ID_MatHang = Convert.ToInt32(gridView1.GetRowCellValue(i, gridView1.Columns["ID_MatHang"]));

                    tblTon ton = new tblTon();
                    ton.ID_MatHang = Convert.ToInt32(gridView1.GetRowCellValue(i, gridView1.Columns["ID_MatHang"]));
                    ton.ID_VatTu = Convert.ToInt32(gridView1.GetRowCellValue(i, gridView1.Columns["ID_VatTu"]));
                    ton.Code = Convert.ToInt32(gridView1.GetRowCellValue(i, gridView1.Columns["Code"]));
                    ton.ID_Kho = Convert.ToInt32(lueKho.EditValue);
                    ton.ID_CCL = Convert.ToInt32(gridView1.GetRowCellValue(i, gridView1.Columns["ID_CCL"]));
                    ton.ID_NguonVatTu = Convert.ToInt32(gridView1.GetRowCellValue(i, gridView1.Columns["ID_NguonVatTu"]));
                    ton.NamSX = Convert.ToString(gridView1.GetRowCellValue(i, gridView1.Columns["NamSX"]));
                    ton.Gia = Convert.ToDouble(gridView1.GetRowCellValue(i, gridView1.Columns["Gia"]));
                    // gia tri Ton ban dau giong nhau = SLTonKH
                    ton.SLTonKH = Convert.ToDouble(gridView1.GetRowCellValue(i, gridView1.Columns["SLKH"])); // SLTonKH += SLKH;
                    ton.SLNhapKH = Convert.ToDouble(gridView1.GetRowCellValue(i, gridView1.Columns["SLKH"]));// SLNhapKH += SLKH;

                    ton.NgayTaoTon = DateTime.Now;
                    ton.SoTheKho = Convert.ToString(gridView1.GetRowCellValue(i, gridView1.Columns["SoTheKho"]));
                    ton.TangKeKhoang = Convert.ToString(gridView1.GetRowCellValue(i, gridView1.Columns["TangKeKhoang"]));
                    if (lueHopDong.EditValue != null)
                        ton.ID_HopDong = Convert.ToInt32(lueHopDong.EditValue);

                    tblSLNX objSLNX = m_SLNX.SelectRecordByID(ID_SLNX);
                    //Update tblTon voi SLKH cũ và trả về ID_MatHang sau khi update
                    ID_MatHang = m_ton.UpdateNhap(ton, Convert.ToDouble(objSLNX.SLKH));

                    tblSLNX _SLNX = new tblSLNX();
                    _SLNX.ID_SLNX = ID_SLNX;
                    _SLNX.ID_MatHang = ID_MatHang;
                    _SLNX.ID_DPNX = _ID_DPNX;
                    _SLNX.SLKH = Convert.ToDouble(gridView1.GetRowCellValue(i, gridView1.Columns["SLKH"]));
                    _SLNX.GhiChu = Convert.ToString(gridView1.GetRowCellValue(i, gridView1.Columns["GhiChu"]) ?? "");
                    _SLNX.ThanhTien = Convert.ToDouble(gridView1.GetRowCellValue(i, gridView1.Columns["ThanhTien"]));
                    m_SLNX.Update(_SLNX);
                }
            }

            KhoiTaoSLNX(obj_DPNX.ID_DPNX);
            KhoiTaoGiaoDien(true);
        }

        private void btnHuy_Click(object sender, EventArgs e)
        {
            if (_ID_DPNX != 0)
            {
                KhoiTaoDPNX();
                KhoiTaoGiaoDien(true);
            }
            else
            {
                lueTCNX.Focus();
                KhoiTaoGiaoDien(false);
                Clear();
            }
        }

        public void Clear()
        {
            //So Phieu Moi
            CKho m_kho = new CKho();
            CModule_Sy module = new CModule_Sy();
            txtSoPhieu.EditValue = module.GetNewSoPhieu("N", DateTime.Now, m_kho.SelectRecordByID(_ID_Kho).KH_Kho, ref _SoPhieu);

            //if (DateTime.Now.Month.ToString().Length == 1)
            //    txtSoPhieu.EditValue = Convert.ToString(GetSoPhieu()) + "/0" + DateTime.Now.Month.ToString() + DateTime.Now.Year.ToString().Substring(2, 2);
            //else
            //    txtSoPhieu.EditValue = Convert.ToString(GetSoPhieu()) + "/" + DateTime.Now.Month.ToString() + DateTime.Now.Year.ToString().Substring(2, 2);

            //Ngay Phieu
            dtpNgayPhieu.EditValue = DateTime.Now;

            txtDonViBan.EditValue = "";
            txtDiaChi.Text = "";
            txtHoaDon.EditValue = "";
            lueKho.EditValue = _ID_Kho;
            _ID_DPNX = 0;
            _ID_DonVi = 0;

            lueHopDong.EditValue = null;
            lueTCNX.EditValue = null;
            txtLyDoNhap.EditValue = "";

            dtSLNX.Rows.Clear();
        }

        public void KhoiTaoGiaoDien(Boolean f)
        {
            txtSoPhieu.Properties.ReadOnly = true;
            txtDiaChi.Properties.ReadOnly = true;
            lueKho.Enabled = false;

            txtDonViBan.Properties.ReadOnly = f;
            txtHoaDon.Properties.ReadOnly = f;
            txtNguoiGiaoNhan.Properties.ReadOnly = f;
            txtLyDoNhap.Properties.ReadOnly = f;

            lueHopDong.Enabled = !f;
            lueTCNX.Enabled = !f;

            dtpNgayPhieu.Properties.ReadOnly = f;
            for (int i = 0; i < gridView1.Columns.Count; i++)
                gridView1.Columns[i].OptionsColumn.AllowEdit = !f;

            gridView1.Columns["VatTu"].OptionsColumn.AllowEdit = false;
            gridView1.Columns["SoTheKho"].OptionsColumn.AllowEdit = false;
            gridView1.Columns["Code"].OptionsColumn.AllowEdit = false;
            gridView1.Columns["ThanhTien"].OptionsColumn.AllowEdit = false;
            gridView1.Columns["MaKyHieu"].OptionsColumn.AllowEdit = false;

            btnThem.Enabled = f;
            btnSua.Enabled = f;
            btnXoa.Enabled = f;
            btnGhi.Enabled = !f;
            btnHuy.Enabled = !f;
        }

        private void gridView1_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.Column.FieldName != "Status")
            {
                try
                {
                    if (Convert.ToInt32(gridView1.GetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns["Status"])) != 1)
                        gridView1.SetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns["Status"], 2);
                    gridView1.UpdateCurrentRow();
                }
                catch { }// bo qua loi them moi
            }

            if (e.Column.FieldName == "Del")
            {
                try
                {
                    Boolean Del = Convert.ToBoolean(gridView1.GetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns["Del"]));
                    int Status = Convert.ToInt32(gridView1.GetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns["Status"]));
                    if (Del == true)
                    {
                        if (Status == 1)
                            gridView1.DeleteRow(gridView1.FocusedRowHandle);
                        else
                            gridView1.SetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns["Status"], 3);

                        gridView1.UpdateCurrentRow();
                    }
                    else
                    {
                        gridView1.SetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns["Status"], 2);
                        gridView1.UpdateCurrentRow();
                    }
                }
                catch { }// bo qua loi them moi
            }
        }

        private void gridView1_RowStyle(object sender, RowStyleEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                int Status = Convert.ToInt32(gridView1.GetRowCellValue(e.RowHandle, gridView1.Columns["Status"]));
                if (Status == 1)//add new
                {
                    //e.Appearance.BackColor = Color.Blue;
                    //e.Appearance.BackColor2 = Color.SeaShell;
                    e.Appearance.Font = new Font(e.Appearance.Font, FontStyle.Bold);
                }
                if (Status == 2)//update row
                {
                    //e.Appearance.BackColor = Color.MediumSpringGreen;
                    //e.Appearance.BackColor2 = Color.SeaShell;
                    e.Appearance.ForeColor = Color.Blue;
                    e.Appearance.Font = new Font(e.Appearance.Font, FontStyle.Italic);
                }
                if (Status == 3)//delete row
                {
                    //e.Appearance.BackColor = Color.Yellow;
                    //e.Appearance.BackColor2 = Color.SeaShell;
                    e.Appearance.ForeColor = Color.Red;
                    e.Appearance.Font = new Font(e.Appearance.Font, FontStyle.Strikeout);
                }
            }
        }

        private void gridView1_ShownEditor(object sender, EventArgs e)
        {
            if (gridView1.FocusedColumn.FieldName.Equals("VatTu"))//Don't work only for this column
            {

                //if (currentEditor != null)
                //{
                //    //AutoCompleteStringCollection customSource = new AutoCompleteStringCollection();                   

                //    currentEditor.MaskBox.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
                //    currentEditor.MaskBox.AutoCompleteSource = AutoCompleteSource.CustomSource;
                //    currentEditor.MaskBox.AutoCompleteCustomSource = customSource;
                //}
            }
            else if (gridView1.FocusedColumn.FieldName.Equals("MaKyHieu"))//Don't work only for this column
            {
                //// tạo autocomplete Mã Ký hiệu với từng loại vật tư
                //TextEdit currentEditor = (sender as GridView).ActiveEditor as TextEdit;
                //currentEditor.MaskBox.AutoCompleteCustomSource = null;

                //if (currentEditor != null)
                //{
                //    AutoCompleteStringCollection MaKyHieuSource = new AutoCompleteStringCollection();
                //    CVatTu m_vattu = new CVatTu();
                //    int ID_VatTu = Convert.ToInt32 (gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "ID_VatTu"));
                //    //MessageBox.Show(VatTu);
                //    var obj_vattu = m_vattu.SelectRecordByID(ID_VatTu);
                //    //kiểm tra tồn tại vật tư trong danh mục hay không
                //    //1. Nếu có thì tạo autocomplete (vật tư đã có trong tồn)
                //    if (obj_vattu != null)
                //    {
                //        var listTon = from p in dc.tblTons
                //                      where p.ID_VatTu == obj_vattu.ID_VatTu
                //                      select p;
                //        foreach (tblTon ton in listTon)
                //        {
                //            MaKyHieuSource.Add(ton.MaKyHieu ?? "");
                //        }
                //        //2. Ngược lại autocomplete = null (vật tư mới)
                //        currentEditor.MaskBox.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
                //        currentEditor.MaskBox.AutoCompleteSource = AutoCompleteSource.CustomSource;
                //        currentEditor.MaskBox.AutoCompleteCustomSource = MaKyHieuSource;
                //    }
                //}
            }
            else { }
        }

        private void gridView1_HiddenEditor(object sender, EventArgs e)
        {
            //if (gridView1.FocusedColumn.FieldName.Equals("VatTu"))
            //{ 
            //    //set ID_VatTu
            //    String VatTu = Convert.ToString(gridView1.GetFocusedRowCellValue("VatTu"));

            //    //if chua ton tai vat tu thi them moi vao trong du lieu
            //    var q = (from p in dc.tblVatTus
            //             where p.VatTu == VatTu
            //             select p).SingleOrDefault();

            //    if (q != null)
            //    {
            //        gridView1.SetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns["ID_VatTu"], q.ID_VatTu);
            //    }
            //    else
            //    {
            //        MessageBox.Show(VatTu);
            //    }


            //}
            if (gridView1.FocusedColumn.FieldName.Equals("Gia") || gridView1.FocusedColumn.FieldName.Equals("SLKH"))
            {
                double Gia, SLKH;
                int i = gridView1.FocusedRowHandle;
                if (gridView1.GetRowCellValue(i, gridView1.Columns["Gia"]) == null)
                {
                    Gia = 0;
                }
                else
                {
                    Gia = Convert.ToDouble(gridView1.GetRowCellValue(i, gridView1.Columns["Gia"]));
                }

                if (gridView1.GetRowCellValue(i, gridView1.Columns["SLKH"]) == null)
                {
                    SLKH = 0;
                }
                else
                {
                    SLKH = Convert.ToDouble(gridView1.GetRowCellValue(i, gridView1.Columns["SLKH"]));
                }
                gridView1.SetRowCellValue(i, gridView1.Columns["ThanhTien"], Gia * SLKH);
            }

        }

        private void btnExcel_Click(object sender, EventArgs e)
        {            
            CModule_Sy sy = new CModule_Sy();
            sy.ToExcel_PhieuNhap(_ID_DPNX);
        }

        private void gridView1_DoubleClick(object sender, EventArgs e)
        {
            if (btnGhi.Enabled == true)
            {
                int ID_Kho = 0;
                try { ID_Kho = Convert.ToInt32(lueKho.EditValue); }
                catch { }
                if (ID_Kho == 0)
                {
                    MessageBox.Show("Bạn chưa chọn Kho cần làm phiếu nhập");
                    lueKho.Focus();
                    return;
                }
                //KhoiTaoGiaoDien(false);
                XtraForm frmTon = new frmVatTuNhap(ID_Kho, this);
                frmTon.ShowDialog();
            }
        }

        #region AutoComplete DonViBan

        AutoCompleteStringCollection donviSource = new AutoCompleteStringCollection();

        public void KhoiTaoAutoCompleteDonVi()
        {
            var listDonVi = from p in dc.tblDonVis
                            where p.Cuoi == true && !(from q in dc.tblKhos select q.ID_DonVi).Contains(p.ID_DonVi)
                            orderby p.DonVi
                            select p;

            //var listKho = from q in dc.tblKhos
            //              select q;

            foreach (tblDonVi donvi in listDonVi)
                donviSource.Add(donvi.DonVi);

            txtDonViBan.MaskBox.AutoCompleteSource = AutoCompleteSource.CustomSource;
            txtDonViBan.MaskBox.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
            txtDonViBan.MaskBox.AutoCompleteCustomSource = donviSource;
        }

        private void txtDonViBan_Enter(object sender, EventArgs e)
        {
            KhoiTaoAutoCompleteDonVi();
        }

        private void txtDonViBan_Leave(object sender, EventArgs e)
        {
            CDonVi m_donvi = new CDonVi();
            tblDonVi objDonVi = m_donvi.SelectRecordByName(Convert.ToString(txtDonViBan.EditValue));
            if (objDonVi == null)
            {
                txtDonViBan.Text = "";
                txtDiaChi.Text = "";
                _ID_DonVi = 0;
                //var frm = new frmMain();
                //frm.AddTab("Danh mục Đơn vị", new ucDonVi());
            }
            else
            {
                _ID_DonVi = objDonVi.ID_DonVi;
                txtDonViBan.EditValue = objDonVi.DonVi;
                txtDiaChi.EditValue = objDonVi.DiaChi;
            }
        }

        private void txtDonViBan_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                txtDiaChi.Focus();
        }

        #endregion

        private void lueHopDong_EditValueChanged(object sender, EventArgs e)
        {
            // change Status for all row in dtgCTPhieuNhap
            for (int i = 0; i < gridView1.RowCount; i++)
            {
                if (Convert.ToInt32(gridView1.GetRowCellValue(i, gridView1.Columns["Status"])) != 1)
                    gridView1.SetRowCellValue(i, gridView1.Columns["Status"], 2);
            }
            gridView1.UpdateCurrentRow();

        }

        private void lueTCNX_VisibleChanged(object sender, EventArgs e)
        {
            lueTCNX.Properties.PopulateColumns();
            lueTCNX.Properties.Columns["ID_TCNX"].Visible = false;
            lueTCNX.Properties.Columns["IsNhap"].Visible = false;
        }

        private void lueHopDong_VisibleChanged(object sender, EventArgs e)
        {
            lueHopDong.Properties.PopulateColumns();
            lueHopDong.Properties.Columns["ID_HopDong"].Visible = false;
            lueHopDong.Properties.Columns["ID_DuAn"].Visible = false;
            lueHopDong.Properties.Columns["NgayKy"].Visible = false;
            lueHopDong.Properties.Columns["TongGiaTri"].Visible = false;
            lueHopDong.Properties.Columns["tblDuAn"].Visible = false;
        }

        private void btPrint_Click(object sender, EventArgs e)
        {
            Thanh.Class.CViewer.InPhieuNhap(_ID_DPNX);
            //if (_ID_DPNX > 0)
            //{
            //    //lấy dữ liệu đổ ra dataset
            //    DataTable dt = new DataTable();
            //    DevEx.Thanh.Utilities.XL_DULIEU.LayDuLieuRaBang("select * from fc_T_LayCTPhieu(" + _ID_DPNX + ")", ref dt);
            //    dt.TableName = "fc_T_LayCTPhieu";
            //    DataSet ds = new DataSet();
            //    ds.Tables.Add(dt);
            //    //in báo cáo
            //    rptPhieuNhap rpt = new rptPhieuNhap();
            //    rpt.DataSource = ds;
            //    //set gia tri cho no
            //    rpt.Parameters["SoPhieu"].Value = txtSoPhieu.Text;
            //    rpt.Parameters["NguoiNhap"].Value = txtNguoiGiaoNhan.Text;
            //    rpt.Parameters["DonVi"].Value = txtDonViBan.Text;
            //    rpt.Parameters["DiaChi"].Value = txtDiaChi.Text;
            //    rpt.Parameters["HoaDon"].Value = txtHoaDon.Text;
            //    rpt.Parameters["Kho"].Value = lueKho.Text;
            //    rpt.Parameters["NgayPhieu"].Value = "Ngày: " + Convert.ToDateTime(dtpNgayPhieu.EditValue).ToString("dd/MM/yyyy");
            //    rpt.Parameters["MucDich"].Value = txtLyDoNhap.Text;
            //    double tongTien = (double)dt.Compute("sum(ThanhTien)", "");
            //    string tienChu = CThanh_Utilities.DocSo(tongTien).Trim();
            //    rpt.Parameters["TienChu"].Value = tienChu;
            //    frmInPhieuOption frm = new frmInPhieuOption(true, rpt, txtNguoiGiaoNhan.Text);
            //    frm.ShowDialog();
            //    //rpt.RequestParameters = false;//bắt buộc hiển thị lên luôn, không chờ nhập parametter
            //    ////gán vào form
            //    ////frmReportViewer frm = new frmReportViewer(rpt);
            //    ////frm.ShowDialog();
            //    //ReportPrintTool pt = new ReportPrintTool(rpt);
            //    //pt.AutoShowParametersPanel = false; //giấu phần hiển thị cho nhập parametter
            //    //pt.ShowPreviewDialog();
            //}
        }

        private void btnRefeshHopDong_Click(object sender, EventArgs e)
        {
            CHopDong m_hopdong = new CHopDong();
            lueHopDong.Properties.DataSource = m_hopdong.SelectAllRecord();
        }

        private void lueHopDong_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                lueHopDong.ClosePopup();
                lueHopDong.EditValue = null;
                e.Handled = true;
            }
        }
    }
}



